package com.nulldev.util.web.nCaptcha.backend;

import java.io.InputStream;
import java.util.HashMap;

import com.nulldev.util.java.DataSet;
import com.nulldev.util.uri.server.RequestType;
import com.nulldev.util.uri.server.v2.HttpPage2;

public class CaptchaPage extends HttpPage2 {

	public CaptchaPage() {
		super("/captcha");
	}
	
	public static final String DATA = "<html>"
			+ "<body>"
			+ "<div style=\"width: 200px; height: 50px; border: 1px solid blue;background-color: black; color: white;\">"
			+ "<noscript>"
			+ "The new nCaptcha requires JavaScript to operate, falling back to legacy."
			+ "</noscript>"
			+ "<div id=\"__cp_0000001\">"
			+ "	<img src=\"/generate_captcha_fallback\" alt=\"You need images enabled, just saying...\"></img>"
			+ "	<p>Click here to read the noScript guide.</p>"
			+ "</div>"
			+ "<div id=\"__cp_js\" style=\"display: none; visibility: hidden;\">"
			+ "<center>"
			+ "<script src=\"/xxtea.js\"></script>"
			+ "<script src=\"/sha256.js\"></script>"
			+ "<script>"
			+ "function uploadData(url, name, data){\n" + 
			"    var xhr = new XMLHttpRequest();\n" + 
			"    var fd = new FormData();\n" + 
			"    xhr.open(\"POST\", url, true);\n" + 
			" 	 xhr.setRequestHeader(name, data);" +
			"    xhr.onreadystatechange = function() {\n" + 
			"        if (xhr.readyState == 4 && xhr.status == 200) {\n" + 
			"            // Every thing ok, file uploaded\n" + 
			"            console.log(xhr.responseText); // handle response.\n" + 
			"        }\n" + 
			"    };\n" + 
			//"    fd.append(name, data);\n" + 
			"    xhr.send();\n" + 
			"}"
			+ "function send_request(url, data, onFail, onSuccess) {\n" + 
			"	if (typeof fetch != \"undefined\") {\n" + 
			"		fetch(url).then(function(response) {\n" + 
			"    		return response.text();\n" + 
			"   	}).then(function(json) {\n" + 
			"   		onSuccess(json);\n" + 
			"   	}).catch(function(ex) {\n" + 
			"   		console.error(ex);\n" + 
			"   		console.error(\"Exception URL: \" + url);\n" + 
			"    		onFail();\n" + 
			"  		});	\n" + 
			"	}else {\n" + 
			"		console.warn(\"send_request() -> Outdated browser found, attempting fallback method...\");\n" + 
			"		var http = null;\n" + 
			"		if (window.XMLHttpRequest) {\n" + 
			"			http = new XMLHttpRequest();		\n" + 
			"		}else {\n" + 
			"			http = new ActiveXObject(\"Microsoft.XMLHTTP\");\n" + 
			"		}\n" + 
			"		http.open('POST', url, true);\n" + 
			"	   http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');\n" + 
			"	   \n" + 
			"	   var hasResponse = false;\n" + 
			"	   //var res = \"\";\n" + 
			"	   http.onreadystatechange = function() {\n" + 
			"		if (http.readyState == 4 && http.status == 200) {\n" + 
			"		//		res = http.responseText;\n" + 
			"				var sp = http.responseText.split(\"\\n\");\n" + 
			"				onSuccess(sp[sp.length - 1]);\n" + 
			"			}\n" + 
			"		}\n" + 
			"		http.ontimeout = function() {\n" + 
			"			alert(\"nTube: onTimeout() was called when fetching your video!\");\n" + 
			"		}\n" + 
			"		http.send(params);\n" + 
			"	}\n" + 
			"	//var http = new XMLHttpRequest();\n" + 
			"	//var params = data;\n" + 
			"	//http.timeout = 0;\n" + 
			"	//http.responseType = 'blob';\n" + 
			"	//http.open('POST', url, true);\n" + 
			"	//http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');\n" + 
			"			\n" + 
			"	//var hasResponse = false;\n" + 
			"	//var res = \"\";\n" + 
			"	//http.onreadystatechange = function() {\n" + 
			"	//	if (http.readyState == 4 && http.status == 200) {\n" + 
			"	//		res = http.responseText;\n" + 
			"	//		onSuccess(http.responseText);\n" + 
			"	//	}\n" + 
			"	//}\n" + 
			"	//http.ontimeout = function() {\n" + 
			"	//	alert(\"nTube: onTimeout() was called when fetching your video!\");\n" + 
			"	//}\n" + 
			"	//http.send(params);\n" + 
			"	\n" + 
			"	/*		\n" + 
			"	var stop = false;\n" + 
			"	var time = 0;\n" + 
			"	while (!hasResponse) {\n" + 
			"		if (stop) {\n" + 
			"			break;\n" + 
			"		}\n" + 
			"		if (time > 1500) {\n" + 
			"			//alert(\"Timeout occured, try again.\");\n" + 
			"			onFail();\n" + 
			"			stop = true;\n" + 
			"		}\n" + 
			"		var ix = -1;\n" + 
			"		time += 1;\n" + 
			"	}*/\n" + 
			"}"
			+ "function run() {"
			+ "send_request(\"/auto_request\", \"\", function () {"
			+ "}, function (data) {"
			+ "	var btnNR = document.getElementById(\"btnNR\");"
			+ " btnNR.disabled = true;"
			+ " btnNR.innerHTML = \"Are you a robot...?\";"
			+ "	var obj = JSON.parse(data);"
			+ " var scr = document.createElement(\"script\");"
			+ " scr.innerHTML = XXTEA.decryptFromBase64(obj.payload, obj.key);"
			+ " document.head.appendChild(scr);"
			+ " var result = window.nCaptchaAuto.payload(obj.key);"
			+ " delete window.nCaptchaAuto;"
			+ " delete window.XXTEA;"
			//+ " console.log(result);"
			+ " uploadData(\"/ncaptcha/auto_upload\", \"data\", result);"
			+ "})"
			+ "}"
			+ "</script>"
			+ "<button id=\"btnNR\" style=\"margin-top: 5%;\" onclick=\"run();\">"
			+ "I'm not a robot"
			+ "</button>"
			+ "</center>"
			+ "</div>"
			+ "<script>"
			+ "document.getElementById(\"__cp_0000001\").style.display = \"none\";"
			+ "document.getElementById(\"__cp_0000001\").style.visibility = \"hidden\";"
			+ "document.getElementById(\"__cp_js\").style = \"\""
			+ "</script>"
			+ "</div>"
			+ "</body>"
			+ "</html>";

	@Override
	public DataSet<Integer, InputStream> request(RequestType type, String url, HashMap<String, String> headers,
			byte[] extraData, String ip) {
		return new DataSet<Integer, InputStream>(200, createStream(DATA));
	}

}
